package org.codehaus.activemq;

import javax.jms.JMSException;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicSession;
import javax.jms.XAConnection;
import javax.jms.XAQueueConnection;
import javax.jms.XAQueueSession;
import javax.jms.XASession;
import javax.jms.XATopicConnection;
import javax.jms.XATopicSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.message.ResponseReceipt;
import org.codehaus.activemq.message.XATransactionInfo;
import org.codehaus.activemq.transport.TransportChannel;
import org.codehaus.activemq.util.IdGenerator;

public class ActiveMQXAConnection extends ActiveMQConnection
  implements XATopicConnection, XAQueueConnection, XAConnection
{
  private static final Log log;
  private final String resourceManagerId;

  public ActiveMQXAConnection(ActiveMQConnectionFactory factory, String theUserName, String thePassword, TransportChannel transportChannel)
    throws JMSException
  {
    super(factory, theUserName, thePassword, transportChannel);
    this.resourceManagerId = determineResourceManagerId();
  }

  public ActiveMQXAConnection(ActiveMQConnectionFactory factory, String theUserName, String thePassword) throws JMSException {
    super(factory, theUserName, thePassword);
    this.resourceManagerId = determineResourceManagerId();
  }

  private String determineResourceManagerId()
    throws JMSException
  {
    XATransactionInfo info = new XATransactionInfo();
    info.setId(this.packetIdGenerator.generateId());
    info.setType(113);

    ResponseReceipt receipt = (ResponseReceipt)syncSendRequest(info);
    String rmId = (String)receipt.getResult();
    assert (rmId != null);
    return rmId;
  }

  public XASession createXASession() throws JMSException {
    return createActiveMQXASession();
  }

  public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException {
    return createActiveMQXASession();
  }

  public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException {
    return createActiveMQXASession();
  }

  public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
    return createActiveMQXASession();
  }

  public XATopicSession createXATopicSession() throws JMSException {
    return createActiveMQXASession();
  }

  public XAQueueSession createXAQueueSession() throws JMSException {
    return createActiveMQXASession();
  }

  protected ActiveMQXASession createActiveMQXASession() throws JMSException {
    checkClosed();
    return new ActiveMQXASession(this);
  }

  public String getResourceManagerId()
  {
    return this.resourceManagerId;
  }

  static
  {
    log = LogFactory.getLog(ActiveMQXAConnection.class);
  }
}